﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietThuongLMS.ViewModels;
using VietThuongLMS.Utils;
using DCS.ComLib.Config;
using VietThuongLMS.Services;
using VietThuongLMS.Areas.Admin.Models;
using System.IO;

///Author: NHDuc 
namespace VietThuongLMS.Areas.Admin.Controllers
{
    public class TinTucController : Controller
    {
        //
        // GET: /Admin/TinTuc/

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Index()
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("Login", "Home", new { area = "Admin" });

            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            TinTucViewModel tinTucList = TinTucService.GetTinTucList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "TinTuc", "Index", "?p=", tinTucList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            return View(tinTucList);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult DanhSachTinTuc(int id)
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("Login", "Home", new { area = "Admin" });

            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            TinTucViewModel tinTucList = TinTucService.GetTinTucList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page, id);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "TinTuc", "Index", "?p=", tinTucList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            ViewData["TenLoaiTinTuc"] = tinTucList.TenLoaiTinTuc;
            //end phân trang

            return View(tinTucList);
        }

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Detail(int id)
        {
            TinTuc tinTuc = TinTucService.GetTinTucById(id);
            return View(tinTuc);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Create()
        {
            using (LMSDataEntities context = new LMSDataEntities())
            {
                IEnumerable<SelectListItem> maMH = new SelectList(context.LoaiTinTucs.ToList(), "ID", "TenLoaiTinTuc");
                ViewData["MaLoaiTinTuc"] = maMH;
            }

            return View();
        }

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(TinTucModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    TinTuc data = new TinTuc();
                    //data.ID = null;
                    data.TieuDe = model.TieuDe;
                    data.NoiDung = model.NoiDung;
                    TaiKhoan tk = new TaiKhoan();
                    tk = AccountService.GetAccountByName(HttpContext.User.Identity.Name);
                    //data.TaiKhoan = tk;
                    data.MaTaiKhoan = tk.ID;
                    data.LuotXem = 0;
                    data.NgayDang = DateTime.Now;
                    data.Tag = "";
                    data.MaLoaiTinTuc = model.MaLoaiTinTuc;
                    data.Deleted = Constant.GENERAL_STATUS_NORMAL;
                    //url
                    if (model.UrlAvatar != null && !model.UrlAvatar.FileName.Equals(""))
                    {
                        if (model.UrlAvatar.ContentLength > 2097152)
                        {
                            ModelState.AddModelError("strUrlAvatar", "(*) Hình ảnh không được phép quá 2MB");
                            return View("Create");
                        }
                        else
                        {
                            string fileName = Path.GetFileName(model.UrlAvatar.FileName);
                            DCS.ComLib.File.Log.Write("NewsControler::Create", "", this.Server.MapPath("~/Images/TinTuc/"));
                            try
                            {
                                //model.image.SaveAs(this.Server.MapPath("~/images/upload" + "//" + fileName));
                                fileName = Utils.Upload.UpdateImageWithSize(model.UrlAvatar, 320, this.Server.MapPath("~/Images/TinTuc/"));
                            }
                            catch (Exception ex)
                            {
                                DCS.ComLib.File.Log.Write("NewsControler::Create", ex.StackTrace, ex.Message);
                            }
                            data.UrlAvatar = fileName;
                        }
                    }
                    ///
                    
                    bool result = TinTucService.InsertTinTuc(data);
                    if (result)
                        return RedirectToAction("Index", "TinTuc", new { area = "Admin" });
                    return View();
                }
                catch (Exception ex)
                {

                }
            }
            return View(model);
        }

        //delete Account
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpGet]
        public ActionResult Delete(int id)
        {
            bool result = TinTucService.DeleteTinTuc(id);
            if (result)
            {
                return RedirectToAction("Index", "TinTuc", new { area = "Admin" });
            }
            else
            {
                return View();
            }

        }

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Edit(int id)
        {
            TinTuc tinTuc = TinTucService.GetTinTucById(id);
            TinTucModel model = (new TinTucConverter()).TinTucToModel(tinTuc);
            //using (LMSDataEntities context = new LMSDataEntities())
            //{
            //    IEnumerable<SelectListItem> loaiLH = new SelectList(context.LoaiTinTucs.ToList(), "ID", "TenLoaiTinTuc");
            //    ViewData["LoaiTinTuc"] = loaiLH;
            //}

            using (LMSDataEntities context = new LMSDataEntities())
            {
                IEnumerable<SelectListItem> maMH = new SelectList(context.LoaiTinTucs.ToList(), "ID", "TenLoaiTinTuc", tinTuc.MaLoaiTinTuc);
                ViewData["MaLoaiTinTuc"] = maMH;
            }
            return View(model);
        }

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(TinTucModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    TinTuc data = new TinTuc();
                    data.ID = model.ID;
                    data.TieuDe = model.TieuDe;
                    data.NoiDung = model.NoiDung;
                    TaiKhoan tk = new TaiKhoan();
                    tk = AccountService.GetAccountByName(HttpContext.User.Identity.Name);
                    data.MaTaiKhoan = tk.ID;
                    data.LuotXem = 0;
                    data.NgayDang = DateTime.Now;
                    //data.Tag = model.Tag;
                    data.MaLoaiTinTuc = model.MaLoaiTinTuc;
                    data.Deleted = Constant.GENERAL_STATUS_NORMAL;
                    //url
                    if (model.UrlAvatar != null &&!model.UrlAvatar.FileName.Equals(""))
                    {
                        if (model.UrlAvatar.ContentLength > 2097152)
                        {
                            ModelState.AddModelError("strUrlAvatar", "(*) Hình ảnh không được phép quá 2MB");
                            return View(model);
                        }
                        else
                        {
                            string fileName = Path.GetFileName(model.UrlAvatar.FileName);
                            DCS.ComLib.File.Log.Write("TinTucController::Edit", "", this.Server.MapPath("~/Images/TinTuc/"));
                            try
                            {
                                //model.image.SaveAs(this.Server.MapPath("~/images/upload" + "//" + fileName));
                                fileName = Utils.Upload.UpdateImageWithSize(model.UrlAvatar, 320, this.Server.MapPath("~/Images/TinTuc/"));
                            }
                            catch (Exception ex)
                            {
                                DCS.ComLib.File.Log.Write("TinTucController::Edit", ex.StackTrace, ex.Message);
                            }
                            data.UrlAvatar = fileName;
                        }
                    }

                    bool result = TinTucService.Edit(data);
                    if (result)
                        return RedirectToAction("Index", "TinTuc", new { area = "Admin" });
                    return View();
                }
                catch (Exception ex)
                {

                }
            }
            return View(model);
        }

    }
}
